package com.ionafan2.iaccepteuromaidan;

import android.os.AsyncTask;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;

public class RequestPostTask extends AsyncTask<String, String, String> {

    private ArrayList<NameValuePair> mData = null;
    private RequestPostTaskListener listener;

    public RequestPostTask setOnRequestTaskListener(RequestPostTaskListener listener) {
        this.listener = listener;
        return this;
    }

    /**
     * constructor
     */
    public RequestPostTask(ArrayList<NameValuePair> data) {
        mData = data;
    }

    /**
     * background
     */
    @Override
    protected String doInBackground(String... params) {
        byte[] result;
        String str = "";
        HttpClient client = new DefaultHttpClient();
        // in this case, params[0] is URL
        HttpPost post = new HttpPost(params[0]);

        try {
            post.setEntity(new UrlEncodedFormEntity(mData, "UTF-8"));
            HttpResponse response = client.execute(post);

            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                result = EntityUtils.toByteArray(response.getEntity());
                str = new String(result, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str;
    }

    /**
     * on getting result
     */
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (listener != null) {
            listener.onDataLoaded(result);
        }
    }
}
